import React, { createRef } from 'react'
import { NavBar, Toast } from 'antd-mobile'
import axios from '../../utils/request'
import { List, AutoSizer } from 'react-virtualized'

import { getCityList } from '../../utils/getCities'
import { getCurrentCity } from '../../utils/getCurrentCity'

import './index.scss'

const TITLE_HEIGHT = 36
const NAME_HEIGHT = 50
const hotCities = ['北京', '上海', '广州', '深圳']

export default class CityList extends React.Component {
  state = {
    cities: {},
    sortArr: [],
    activeIndex: 5
  }

  listRef = createRef()

  async componentDidMount() {
    //获取所有城市列表
    await this.getCities()
    this.listRef.current.measureAllRows()
  }

  async getCities() {
    const city = await getCityList()
    // console.log(city)
    //拿到分好类的城市列表
    //通过城市列表的keys值拿到排序数组
    const arr = ['#', 'hot', ...Object.keys(city).sort()]
    // console.log(arr)
    //获取当前城市并设置
    const currentCity = await getCurrentCity()
    // console.log(currentCity)
    city['#'] = [currentCity]
    // console.log(currentCity)
    //获取热门城市
    const { body } = await axios.get('/area/hot')
    // console.log(body)
    city.hot = body
    this.setState({
      cities: city,
      sortArr: arr
    })
  }

  rowRenderer = ({ key, index, isScrolling, isVisible, style }) => {
    // console.log(this.state)
    const { sortArr, cities } = this.state
    // console.log(cities)
    const cityCateName = sortArr[index]
    // console.log(cities[cityCateName])
    // console.log(this.state.sortArr[index].toUpperCase())
    return sortArr.map(e => {
      return (
        <div key={e} style={style} className="city">
          <div className="title">{this.renderTitle(cityCateName)}</div>
          {cities[cityCateName].map(e => {
            return (
              <div
                className="name"
                key={e.value}
                onClick={() => {
                  this.handleClick(e.label)
                }}
              >
                {e.label}
              </div>
            )
          })}
        </div>
      )
    })
  }

  // 创建动态计算每一行高度的方法
  getRowHeight = ({ index }) => {
    // 索引标题高度 + 城市数量 * 城市名称的高度
    // TITLE_HEIGHT + cityList[cityIndex[index]].length * NAME_HEIGHT
    const { cities, sortArr } = this.state
    return TITLE_HEIGHT + cities[sortArr[index]].length * NAME_HEIGHT
  }

  renderTitle(e) {
    switch (e) {
      case '#':
        return '当前城市'
      case 'hot':
        return '热门城市'
      default:
        return e.toUpperCase()
    }
  }

  onRowsRendered = ({
    overscanStartIndex,
    overscanStopIndex,
    startIndex,
    stopIndex
  }) => {
    // console.log(startIndex)
    if (startIndex === this.state.activeIndex) return
    this.setState({
      activeIndex: startIndex
    })
  }

  changeActive = index => {
    // console.log(index)
    // this.setState({ activeIndex: index })
    this.listRef.current.scrollToRow(index)
  }

  handleClick = async current => {
    // console.log(current)
    if (hotCities.indexOf(current) === -1) {
      // console.log(111)
      Toast.info('暂无房源', 1.5, null, true)
    } else {
      const { body } = await axios(`/area/info?name=${current}`)
      // console.log(body)
      localStorage.setItem('hzk_city', JSON.stringify(body))
      this.props.history.push('/')
    }
  }

  render() {
    // console.log(this.state.cities)
    // console.log(this.state.sortArr)
    return (
      <div className="cityBox">
        <NavBar
          mode="light"
          icon={<i className="iconfont icon-back"></i>}
          onLeftClick={() => this.props.history.push('/')}
        >
          城市选择
        </NavBar>
        <AutoSizer className="cityList">
          {({ height, width }) => {
            // console.log(this.state.sortArr.length)
            return (
              <List
                width={width}
                height={height}
                rowCount={this.state.sortArr.length}
                rowHeight={this.getRowHeight}
                rowRenderer={this.rowRenderer}
                onRowsRendered={this.onRowsRendered}
                ref={this.listRef}
                scrollToAlignment="start"
              />
            )
          }}
        </AutoSizer>
        <ul className="city-index">
          {this.state.sortArr.map((e, index) => {
            // console.log(e)
            return (
              <li
                className="city-index-item"
                key={e}
                onClick={() => {
                  this.changeActive(index)
                }}
              >
                <span
                  className={
                    this.state.activeIndex === index ? 'index-active' : ''
                  }
                >
                  {e === 'hot' ? '热' : e.toUpperCase()}
                </span>
              </li>
            )
          })}
        </ul>
      </div>
    )
  }
}
